package com.ctrl.riveradministrator.mvp.view.activity.main;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.base.BaseFragment;
import com.ctrl.riveradministrator.base.BaseListAdapter;
import com.ctrl.riveradministrator.mvp.model.News;
import com.ctrl.riveradministrator.mvp.presenter.NewsPresenter;
import com.ctrl.riveradministrator.mvp.view.activity.news.NewsAdapter;
import com.ctrl.riveradministrator.mvp.view.activity.news.NewsDetailActivity;
import com.ctrl.riveradministrator.mvp.view.activity.news.NewsView;

import java.util.ArrayList;
import java.util.List;


public class HomeFragment extends BaseFragment<NewsPresenter>
        implements ViewPager.OnPageChangeListener, NewsView,
        BaseListAdapter.OnItemClickListener<News> {

    public static HomeFragment INSTANCE;
    private SharedPreferences sp;
    private ViewPager viewPager;
    private int[] imageResIds;
    private List<ImageView> imageViews;
    private LinearLayout llPointContainer;
    private int previousSelectedPos = 0;
    boolean isRunning = false;

    private RecyclerView bulletinRl;
    private SwipeRefreshLayout bulletinSfl;
    private LinearLayoutManager layoutManager;
    private NewsAdapter newsAdapter;

    private List<News> news = new ArrayList<>();
    private static int currentPage;


    public static HomeFragment newInstance() {
        if (INSTANCE == null) {
            INSTANCE = new HomeFragment();
        }
        return INSTANCE;
    }

    public HomeFragment() {
    }


    @Override
    protected int bindLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view) {
        viewPager = $(view, R.id.viewpager);
        llPointContainer = $(view, R.id.ll_point_container);
        bulletinRl = $(view, R.id.bulletin_list);
        bulletinSfl = $(view, R.id.bulletin_srl);

        layoutManager = new LinearLayoutManager(getContext());
        bulletinRl.setLayoutManager(layoutManager);
        bulletinSfl.setColorSchemeColors(Color.RED, Color.BLUE);
        bulletinSfl.setEnabled(false);
        newsAdapter = new NewsAdapter(getContext());
        bulletinRl.setAdapter(newsAdapter);

    }

    @Override
    protected void doBusiness(Context mContext, Activity activity) {
        initData();
        initAdapter();
        new Thread(() -> {
            isRunning = true;
            while (isRunning) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 往下跳一位
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
//                    System.out.println("设置当前位置: " + viewPager.getCurrentItem());
                        viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                    });
                }
            }
        }).start();
        currentPage = 0;
        mPresenter.getNews(currentPage + "", "20");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }

    @Override
    protected void widgetClick(View view) {

    }

    @Override
    protected void setListener() {
        viewPager.addOnPageChangeListener(this);
       /* bulletinRl.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (bulletinRl.computeVerticalScrollOffset() > 0 && bulletinRl.computeVerticalScrollExtent() + bulletinRl.computeVerticalScrollOffset()
                            >= bulletinRl.computeVerticalScrollRange()) {
                        currentPage = currentPage + 20;
                        mPresenter.getNews("" + currentPage, "20");
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });*/
        newsAdapter.setOnItemClickListener(this);
    }

    @Override
    public void handleMessage(Message message, int what) {

    }

    @Override
    protected NewsPresenter createPresenter() {
        return new NewsPresenter(this);
    }

    private void initData() {
        // 图片资源id数组
//        imageResIds = new int[]{R.mipmap.b1, R.mipmap.b2, R.mipmap.b3, R.mipmap.b4, R.mipmap.b5};
        imageResIds = new int[]{R.mipmap.b11, R.mipmap.b22};

        // 文本描述

        // 初始化要展示的5个ImageView
        imageViews = new ArrayList<ImageView>();

        ImageView imageView;
        View pointView;
        LinearLayout.LayoutParams layoutParams;
        for (int i = 0; i < imageResIds.length; i++) {
            // 初始化要显示的图片对象
            imageView = new ImageView(getContext());
            imageView.setBackgroundResource(imageResIds[i]);
            imageViews.add(imageView);

            // 加小白点, 指示器
            pointView = new View(getContext());
            pointView.setBackgroundResource(R.drawable.ic_brightness_1_black_24dp);
            layoutParams = new LinearLayout.LayoutParams(10, 10);
            if (i != 0)
                layoutParams.leftMargin = 10;
            // 设置默认所有都不可用
            pointView.setEnabled(false);
            llPointContainer.addView(pointView, layoutParams);
        }
    }

    private void initAdapter() {
        llPointContainer.getChildAt(0).setEnabled(true);
        previousSelectedPos = 0;

        // 设置适配器
        viewPager.setAdapter(new PageAdapter());

        // 默认设置到中间的某个位置
        int pos = Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2 % imageViews.size());
        // 2147483647 / 2 = 1073741823 - (1073741823 % 5)
        viewPager.setCurrentItem(5000000); // 设置到某个位置
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {
        // 新的条目被选中时调用
//        System.out.println("onPageSelected: " + i);
        int newPosition = i % imageViews.size();

//		for (int i = 0; i < ll_point_container.getChildCount(); i++) {
//			View childAt = ll_point_container.getChildAt(position);
//			childAt.setEnabled(position == i);
//		}
        // 把之前的禁用, 把最新的启用, 更新指示器
        llPointContainer.getChildAt(previousSelectedPos).setEnabled(false);
        llPointContainer.getChildAt(newPosition).setEnabled(true);
        llPointContainer.getChildAt(previousSelectedPos).setBackgroundResource(R.drawable.ic_brightness_1_black_24dp);
        llPointContainer.getChildAt(newPosition).setBackgroundResource(R.drawable.ic_brightness_1_w_24dp);

        // 记录之前的位置
        previousSelectedPos = newPosition;
    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    @Override
    public void showMessage(List<News> bulletins) {
        this.news.addAll(bulletins);
        newsAdapter.updateListView(this.news);
    }

    @Override
    public void onItemClick(News news, int position) {
        startActivity(new Intent(getActivity(), NewsDetailActivity.class).putExtra("news", news));
    }

    class PageAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
            return view == o;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
//            System.out.println("instantiateItem初始化: " + position);
            // container: 容器: ViewPager
            // position: 当前要显示条目的位置 0 -> 4

            //newPosition = position % 5
            int newPosition = position % imageViews.size();

            ImageView imageView = imageViews.get(newPosition);
            //先移除子控件再添加，避免The specified child already has a parent. You must call removeView错误
            container.removeView(imageView);
            // a. 把View对象添加到container中
            container.addView(imageView);
            // b. 把View对象返回给框架, 适配器
            return imageView; // 必须重写, 否则报异常
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        }
    }
}
